<template>
    <el-dialog
        title="图纸选择"
        :visible="visible"
        width="700px"
        custom-class="doc-custom-dialog"
        :close-on-click-modal="false"
        @closed="closed"
        @open="dialogOpen"
        @close="onClose"
    >
        <vxe-toolbar>
          <template #buttons>
              <div class="toolbar">
                <div style="width: 59%">
                    <el-button size="small" @click="addNewLine()" type="success">新增</el-button>
                    <span style="margin-left: 16px">过滤:</span>
                    <el-radio-group v-model="filter" size="small" class="radio-group">
                        <el-radio-button label="all" content="全部">全部</el-radio-button>
                        <el-radio-button label="selected" content="已选择">已选择</el-radio-button>
                        <!-- <el-radio-button label="unselected" content="未选择">未选择</el-radio-button> -->
                    </el-radio-group>
                </div>
                <div style="width: 40%;">
                    <el-input
                        placeholder="请输入图纸名称或编号"
                        clearable
                        v-model="filterText"
                        @change="search"
                    >
                        <el-button
                            @click="search" slot="append" icon="el-icon-search"></el-button>
                    </el-input>

                </div>
              </div>
          </template>
        </vxe-toolbar>
        <vxe-table
            border
            ref="xTable"
            :keep-source="false"
            :data="docData"
            max-height="500px"
            row-id="dataid"
            resizable
            auto-resize
            :checkbox-config="{trigger: 'cell', reserve: true }"
            highlight-hover-row
            @edit-actived="editActivedEvent"
            @checkbox-change="handleCheckedChange"
            @checkbox-all="handleCheckedChange"
            :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
        >
            <!-- :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"  -->
            <vxe-table-column type="checkbox" title="" width="40"></vxe-table-column>
            <vxe-table-column
                field="docname"
                title="图纸名称"
                :edit-render="{
                    name: 'input',
                    attrs: {
                        disabled: rowStatus.docnameDisabled
                    }
                }"
            ></vxe-table-column>
            <vxe-table-column
                field="doccode"
                title="图纸编号"
                :edit-render="{
                    name: 'input',
                    attrs: {
                        disabled: rowStatus.doccodeDisabled
                    }
                }"
            ></vxe-table-column>
            <vxe-table-column
                field="docver"
                title="图纸版本"
                :edit-render="{
                    name: 'input',
                    attrs: {
                        disabled: rowStatus.docverDisabled,
                    }
                }"
            ></vxe-table-column>
            <vxe-table-column title="操作">
                <template v-slot="{ row, rowIndex }">
                    <!-- 如果能编辑，那么表明是手动输入的 -->
                    <template v-if="row.canEdit">
                        <el-button circle icon="el-icon-check" size="small"></el-button>
                        <el-button circle icon="el-icon-delete" size="small" @click="deleteLine(rowIndex)"></el-button>
                    </template>
                    <template v-else>
                        <el-button type="text" size="small" ctrl-code="BSC" @click="lookFile">查看</el-button>
                    </template>
                </template>
            </vxe-table-column>
        </vxe-table>
        <template #footer>
            <div>
                <el-button type="primary" @click="handleSubmit">确 定</el-button>
                <el-button @click="onClose">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script>
/**
 * all 全部，selected 已选中, unselected 未选中
 */
// const filterTypes = ['all', 'selected', 'unselected']

export default {
    data() {
        return {
            docData: [],
            rowStatus: {
                docnameDisabled: false,
                doccodeDisabled: false,
                docverDisabled: false,
            },
            dataSource:[],
            filter: 'all',
            filterText: '',
            // 选择的图纸
            selection: []
        }
    },
    props: {
        visible: {
            type: Boolean,
            default: false,
        },
        onClose: {
            type: Function,
            default: () => {}
        },
        onOk: {
            type: Function,
            default: () => {}
        },
        // 需要一个containerOid参数
        containerOid: {
            type: String,
            default: ''
        },
        // 需要获取当前选择的表格行数据
        selectedRow: {
            type: Object,
            default: () => ({})
        },
        // look file
        lookFile: {
            type: Function,
            default: () => {}
        },
        readonly: {
            type: Boolean,
            default: false,
        }
    },
    methods: {
        async addNewLine() {
            this.docData=[{
                canEdit: true
            }, ...this.docData];
            this.$nextTick(async function() {
                const newRow = this.$refs.xTable.getData(0);
                await this.$refs.xTable.setActiveCell(newRow, 'docname');
            })
        },
        async insertEvent () {
            let record = { canEdit: true };
            let { row: newRow } = await this.$refs.xTable.insertAt(record);
            await this.$refs.xTable.setActiveCell(newRow, 'docname');
        },
        deleteLine(rowIndex) {
            console.log('rowIndex  ', rowIndex);
            this.docData = this.docData.filter((row, index) => index !== rowIndex);
        },
        // activeRowMethod ({ row }) {
        //     console.log('row row ', row);
        //     return Boolean(row.canEdit);
        // },
        editActivedEvent ({ row }) {
            const status = this.rowStatus;
            const disabled = !row.canEdit
            status.docnameDisabled = disabled;
            status.doccodeDisabled = disabled;
            status.docverDisabled = disabled;
        },
        dialogOpen() {
            // 查询图纸列表
            let url = "/pms/PmsViewDocList/getByContaineroid";
            let docIds = this.selectedRow.docIds ? this.selectedRow.docIds : '';
            let defaultChecked = [];
            this.$axios.get(url, {params: {containeroid: this.containerOid}})
                .then(result => {
                    let docData = Array.isArray(result.data) ? result.data : [];
                    this.docData = docData;
                    // datasoure用于数据被过滤后恢复所有数据
                    this.dataSource = docData;
                    if (docIds) {
                        defaultChecked = docData.filter((item) => docIds.indexOf(item.docid) > -1);
                    } else if (!(!docIds && this.selectedRow.docChanged)) {
                        // 如果没有选择过，默认选中reat值等于1的
                        defaultChecked = docData.filter((item) => item.reat === '1');
                    }
                    this.$nextTick(() => {
                        this.$refs.xTable.clearCheckboxRow();
                        defaultChecked.forEach(it => {
                            this.$refs.xTable.setCheckboxRow(it, true);
                        });
                    })
                    if (this.readOnly) {
                        this.docData = defaultChecked;
                    }
                }).catch(error => {
                    console.error(error);
                    this.$message.error("查询产品图纸失败！")
                })
        },
        closed() {
            // 关闭以后重置组件的数据
            this.filter = 'all';
        },
        search() {
            const searchText = (this.filterText || '').trim().toLowerCase();
            if (searchText) {
                const rest = this.dataSource.filter(item => {
                    const temp = item.docname + item.doccode;
                    return temp.indexOf(searchText) > -1;
                })
                // 搜索的时候过滤按钮重置为全部
                this.filter = 'all';
                this.docData = rest;
            }
        },
        clearFilter() {
            this.docData = this.dataSource;
        },
        handleCheckedChange(event) {
            this.selection = event.selection;
        },
        handleSubmit() {
            this.onOk(this.selection)
        }
    },
    watch: {
        filterText: function(newVal, oldVal) {
            // 当输入框为空的时候 重置表格的数据
            if (oldVal && !newVal) {
                this.clearFilter();
            }
        },
        filter: function(newVal) {
            // ['all', 'selected', 'unselected']
            // 如果filterText是有值的，那么filter的过滤被忽略
            if (this.filterText) return;
            if (newVal === 'all') {
                this.docData = this.dataSource;
            }
            if (newVal === 'selected') {
                // console.log('getCheckboxReserveRecords', this.$refs.xTable.getCheckboxReserveRecords())
                // console.log('getCheckboxRecords', this.$refs.xTable.getCheckboxRecords())
                this.docData = this.selection;
            }
            // 目前看来未选择会有很多问题，还不大清楚vxe-table怎么处理这些选中的数据的
            // if (newVal === 'unselected') {
            //     this.docData = this.dataSource.filter((item) => !(this.selection.find(it => it.dataid === item.dataid)))
            //     console.log(this.selection);
            // }
        }
    }
}
</script>

<style scoped lang="less">
    .radio-group{
        margin-left: 8px;
    }
    .toolbar {
        display: flex;
        justify-content: space-around;
    }
</style>
<style lang="less">
    .doc-custom-dialog .el-dialog__body {
        padding: 10px 20px !important;
        min-height: 300px;
    }
</style>